<?php
/**
 * 作者：亮 www.520internet.com
 **/

//	[定义变量]
    define('Mi18n', true);
    //error_reporting(E_ALL);
    session_start();
    error_reporting(0);

//	[私有配置]
    $pRootUrl = './';
    // 翻译数据文件 URL
    define('SQLITE_DATABASE_FILE_PATH', './data/data.sqlite3');
    define('SQLITE_PASSWORD', 'mi18n');

//	[加载文件]
    require $pRootUrl.'msqlite.class.php';
    require $pRootUrl.'mi18n.class.php';
    $Mi18nObj = new Mi18n();

//  [请求限制]
    /*
    $origin = parse_url($_SERVER['HTTP_REFERER']);
    $Mi18nObj->setTableName('website');
    $allowOrigin = $Mi18nObj->get('domain', $origin['host'], true);
    if ($allowOrigin) {
    	header("Access-Control-Allow-Origin:".$origin);
    }
    */
   header("Access-Control-Allow-Origin: *");

//  [处理数据]
    // 添加
    if ($_GET['action'] == 'insertMi18n') {
        $language = json_decode(htmlspecialchars_decode($_POST['language'], ENT_QUOTES));
        foreach ($language as $sourceLanguage) {
            $sourceLanguage = $sourceLanguage ? $sourceLanguage : '--';
            $languageArr = array(
              'key' => md5($sourceLanguage),
              'source' => $sourceLanguage,
              'page' => $_POST['page'],
              'website' => $_POST['website'],
              'created_datetime' => date('Y-m-d H:i:s'),
              'last_update_datetime' => date('Y-m-d H:i:s')
            );
            $Mi18nObj->setTableName('mi18n');
            $Mi18nObj->insert($languageArr);
        }
        exit('{"status":"200", "message":"成功"}');
    }

    // 更新
    if ($_GET['action'] == 'updateMi18n') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('mi18n');
        if ($Mi18nObj->updateByField('key', $_POST['key'], array($_POST['language'] => $_POST['content'], 'last_update_datetime' => date('Y-m-d H:i:s')))) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 获取语言
    if ($_GET['action'] == 'getMi18n') {
        $Mi18nObj->setTableName('mi18n');
        $result = $Mi18nObj->get('website', $_GET['website'] ? $_GET['website'] : '', true);
        foreach ($result as $key => $value) {
          if ($_GET['page'] && $_GET['page'] == $value['page']){
            foreach ($value as $keys => $values) {
              $languageArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
            }
          } else {
            foreach ($value as $keys => $values) {
              $languageArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
            }
          }
        }
        if (!$languageArr) {
            $languageArr[0] = array();
        }
        exit(json_encode($languageArr));
    }

    // 获取翻译列表
    if ($_GET['action'] == 'getListMi18n') {
        // 处理排序与GET参数
        $orderbyArr = array('created_datetime');
        $orderby = in_array($_GET['orderby'], $orderbyArr) ? $_GET['orderby'] : $orderbyArr[0];
        $ade = strtolower($_GET['ade']) == 'asc' ? 'asc' : 'desc';

        // 搜索
        $where = '';
        if ($_GET['field'] && $_GET['sc']) {
            $where = "AND `".$_GET['field']."` LIKE '%".$Mi18nObj->dbObj->escapeString($_GET['sc'])."%'";
        }
        if ($_GET['website'] && $_GET['website'] != 'all') {
            $where .= "AND `website` = '".$Mi18nObj->dbObj->escapeString($_GET['website'])."'";
        }
        $order = array($orderby, $ade);
        $page = is_numeric($_GET['page']) ? $_GET['page'] : 1;
        $limit = is_numeric($_GET['limit']) ? $_GET['limit'] : 10;
        $Mi18nObj->setTableName('mi18n');
        $languageArr = $Mi18nObj->getList($where, $order, $limit, $page);
        exit(json_encode($languageArr));
    }

    // 删除
    if ($_GET['action'] == 'deleteMi18n') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('mi18n');
        if ($Mi18nObj->delete('key', $_GET['key'])) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 清空
    if ($_GET['action'] == 'deleteAllMi18n') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('mi18n');
        if ($Mi18nObj->deleteAll()) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 获取语种列表
    if ($_GET['action'] == 'getLanguage') {
        $Mi18nObj->setTableName('language');
        $result = $Mi18nObj->get('page', $_GET['page'], true);
        foreach ($result as $key => $value) {
            foreach ($value as $keys => $values) {
                $languageArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
            }
        }
        if (!$languageArr) {
            exit;
        }
        exit(json_encode($languageArr));
    }

    // 添加语种
    if ($_GET['action'] == 'addLanguage') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $languageArr = array(
          'index' => $_POST['index'],
          'name' => $_POST['name']
        );
        $Mi18nObj->dbObj->query("alter table `mi18n` add `".$_POST['index']."` TEXT");
        $Mi18nObj->setTableName('language');
        if ($Mi18nObj->insert($languageArr)) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 更新语种
    if ($_GET['action'] == 'updateLanguage') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('language');
        if ($Mi18nObj->updateByField('index', $_POST['index'], array('name' => $_POST['name']))) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 删除语种
    if ($_GET['action'] == 'deleteLanguage') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('language');
        if ($Mi18nObj->delete('index', $_GET['index'])) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 获取管理员
    if ($_GET['action'] == 'getAdmin') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('admin');
        $result = $Mi18nObj->get('page', $_GET['page'], true);
        foreach ($result as $key => $value) {
            foreach ($value as $keys => $values) {
                $adminArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
            }
        }
        if (!$adminArr) {
            $adminArr[0] = array();
        }
        exit(json_encode($adminArr));
    }
    // 管理员登录
    if ($_GET['action'] == 'login'){
      $Mi18nObj->setTableName('admin');
      if ($_POST['username'] != ''){
        $result = $Mi18nObj->get('username', $_POST['username'], false);
        if (!$result) {
          exit('{"status":"500", "message":"管理员账号错误"}');
        }

        if (md5($_POST['password'].'mi18n') == $result['password']){
          $_SESSION['login'] = '1';
          exit('{"status":"200", "message":"登录成功"}');
        } else {
          exit('{"status":"500", "message":"密码不正确"}');
        }
      }
      exit('{"status":"500", "message":"错误"}');
    }
    // 验证是否登录
    if ($_GET['action'] == 'isLogin'){
        if ($_SESSION['login'] == '1'){
          exit('{"status":"200", "message":"已登录"}');
        } else {
          exit('{"status":"500", "message":"未登录"}');
        }
    }
    // 退出
    if ($_GET['action'] == 'logout'){
        $_SESSION['login'] = '';
        exit('{"status":"200", "message":"成功"}');
    }
    // 添加管理员
    if ($_GET['action'] == 'addAdmin') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $dataArr = array(
          'username' => $_POST['username'],
          'password' => md5($_POST['password'].'mi18n')
        );
        $Mi18nObj->setTableName('admin');
        if ($Mi18nObj->insert($dataArr)) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }
    // 删除管理员
    if ($_GET['action'] == 'deleteAdmin') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        if ($_GET['id'] == '1'){
          exit('{"status":"500", "message":"不能删除管理员"}');
        }

        $Mi18nObj->setTableName('admin');
        if ($Mi18nObj->delete('id', $_GET['id'])) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }
    // 更新密码
    if ($_GET['action'] == 'changePassword') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        if (empty($_POST['oldPassword']) || empty($_POST['newPassword'])){
          exit('{"status":"500", "message":"原密码与新密码不能为空"}');
        }

        $Mi18nObj->setTableName('admin');

        $result = $Mi18nObj->get('username', $_POST['username'], false);
        if (md5($_POST['oldPassword'].'mi18n') != $result['password']){
          exit('{"status":"500", "message":"原密码错误"}');
        }

        if ($Mi18nObj->updateByField('id', $_POST['id'], array('password' => md5($_POST['newPassword'].'mi18n')))) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }
    // 获取网站列表
    if ($_GET['action'] == 'getWebsite') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('website');
        $result = $Mi18nObj->get('page', $_GET['page'], true);
        foreach ($result as $key => $value) {
            foreach ($value as $keys => $values) {
                $websiteArr[$key][$keys] = htmlspecialchars_decode($values, ENT_QUOTES);
            }
        }
        if (!$websiteArr) {
            $websiteArr[0] = array();
        }
        exit(json_encode($websiteArr));
    }

    // 更新
    if ($_GET['action'] == 'updateWebsite') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('website');
        if ($Mi18nObj->updateByField('id', $_POST['id'], array('domain' => $_POST['domain']))) {
            exit('{"status":"200", "message":"成功"}');
        } else {
            exit('{"status":"500", "message":"错误"}');
        }
    }

    // 下载翻译数据
    if ($_GET['action'] == 'downloadMi18n') {
        if ($_SESSION['login'] != '1'){
          exit('{"status":"500", "message":"未登录"}');
        }
        $Mi18nObj->setTableName('mi18n');
        $Mi18nObj->download();
    }
